<template>
  <el-form ref="formRef" :model="_form" :rules="rules" label-width="80px" size="small">
    <el-form-item label="数据值" prop="value">
      <el-input v-model.trim="_form.value" size="small" />
    </el-form-item>
    <el-form-item label="辅助值1" prop="valueOth1">
      <el-input v-model.trim="_form.valueOth1" size="small" />
    </el-form-item>
    <el-form-item label="辅助值2" prop="valueOth2">
      <el-input v-model="_form.valueOth2" size="small" />
    </el-form-item>
    <el-form-item label="锁定" prop="lockUp">
      <el-checkbox v-model="_form.lockUp" />
    </el-form-item>
    <remark v-model:remark="_form.remark" :size="300" />
    <el-form-item>
      <drawer-footer :save-loading="saveLoading" @cancel="cancel" @confirm="confirm" />
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { computed, defineEmits, defineExpose, defineProps, ref } from 'vue'

import { ElMessage } from 'element-plus'

import DrawerFooter from '&/components/DrawerFooter/index.vue'
import Remark from '&/components/Form/remark.vue'

import DictApi from '@/api/backend/dict'

import IBaseObj from '#/index'

const props = defineProps({
  data: {
    type: Object,
    default: () => {},
  },
  form: {
    type: Object,
    default: () => {},
  },
  isAdd: {
    type: Boolean,
    default: true,
  },
})
const emits = defineEmits(['update:form', 'cancel', 'confirm'])

const rules = {
  value: [{ required: true, message: '请输入数据值', trigger: 'blur' }],
}

const saveLoading = ref(false)

const _form: IBaseObj = computed({
  get() {
    return props.form
  },
  set(val) {
    emits('update:form', val)
  },
})

const cancel = () => {
  emits('cancel')
}

const formRef = ref()
const confirm = () => {
  formRef.value.validate(async (valid: Boolean) => {
    if (valid) {
      saveLoading.value = true
      try {
        let res = null
        const status = _form.value.status ? 1 : 0
        const params = {
          catalogId: props.data.id,
          catalogCode: props.data.code,
        }
        console.log('_form', _form.value)
        res = await DictApi.saveDictContent({ ..._form.value, ...params, status })

        const { status: statusCode } = res
        if (statusCode === 200) {
          if (props.isAdd) {
            ElMessage({ message: '创建成功!', type: 'success', duration: 1500 })
          } else {
            ElMessage({ message: '修改成功!', type: 'success', duration: 1500 })
          }
          emits('confirm')
        }
      } catch (error) {
        console.log(error)
      } finally {
        saveLoading.value = false
      }
    } else {
      return false
    }
  })
}

const clear = () => {
  formRef.value.resetFields()
}

defineExpose({
  clear,
})
</script>

<style lang="scss" scoped></style>
